<template>
  <div class="am-u-sm-12 am-u-md-12 am-u-lg-12 m-fee-add" >
    <div class="widget am-cf">
      <div class="widget-head am-cf">
        <div class="widget-title am-fl">添加小类</div>
        <div class="widget-function am-fr">
          <button type="button" class="am-btn am-btn-default" @click="$router.go(-1)">返回</button>
        </div>
      </div>
      <div class="widget-body am-fr">
        <el-form class="tpl-form-border-form tpl-form-border-br" ref="form" label-width="300px">
          <el-form-item v-for="(item, index) in list" class="list-item am-form-group" prop="categoryName" :label="'来源小类' + (index + 1)">
            <el-input v-model="item.categoryName" size="small"></el-input>
          </el-form-item>
          <el-form-item class="list-item am-form-group" label=" ">
            <el-button type="success" size="small" @click="handleAdd">增加</el-button>
            <el-button type="success" size="small" @click="handleDel" :disabled="list.length === 0">减少</el-button>
          </el-form-item>
        </el-form>
        <div class="am-form-group" style="text-align: center">
          <button type="button" size="big" class="am-btn am-btn-primary" @click="handleSave">保存</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import io from '../../lib/io'
  import moment from 'moment'

  export default{
    components: {},
    data(){
      return{
        list: [{
          categoryName: ''
        }],
      }
    },
    created:function(){
      this.parentFromCategoryId = this.$route.query.categoryId
      this.loadTableData(this.parentFromCategoryId)
    },
    methods:{
      handleSave () {
        let categoryNames = []
        this.list.map(val => {
          if (val.categoryName) {
            categoryNames.push(val.categoryName)
          }
        })
        io.post(io.saveOrUpdateSmallFromCategory, {
          parentFromCategoryId: this.parentFromCategoryId,
          categoryNames: categoryNames,
        }, (ret) => {
          if (ret.success) {
            this.$toast('保存成功！')
            this.$router.go(-1)
          } else {
            this.$alert(ret.desc)
          }
        })
      },
      loadTableData (bigFromCategory) {
        io.post(io.smallFromCategory, {
          bigFromCategory: bigFromCategory
        }, (ret) => {
          if (ret.success) {
            this.list = ret.data
            if (ret.data.length === 0) {
              this.handleAdd()
            }
          } else {
            this.$alert(ret.desc)
          }
        })
      },
      handleAdd () {
        this.list.push({categoryName: ''})
      },
      handleDel () {
        this.list.pop()
      },
    }
  }
</script>

<style lang="less">
  .m-fee-add {
    .am-form-success label {
      color: #666;
    }
    .el-checkbox-group {
      .el-checkbox:first-child {
        margin-left: 15px;
      }
    }
  }
</style>
